import threading
import math
import re
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from collections import OrderedDict
from rest_framework.authentication import (
    get_authorization_header
)
from django.utils.encoding import smart_text

from rest_framework.response import Response

from rest_framework.pagination import PageNumberPagination

from .models import WomaiOrder, OrderIncome, SupplyOrder
from .womai_api import WoMaiApi
from core.tools.short_message import ShortMessage

wo_mai = WoMaiApi()
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER


def check_update_order(obj):
    if obj.check_status == 0:
        # 第一次查询判断是否需要拆单
        response = wo_mai.get_trade(obj.tid)
        WomaiOrder.objects.update_order(response, obj)
    # 更新其他状态
    elif obj.check_status == 1 or obj.check_status == 2:
        response = wo_mai.get_trade(obj.tid)
        obj.update_search_result(response)
    # 被拆过的订单(不需要展示)
    else:
        pass


def create_income(s_order):
    parent_order = s_order.main_base_order.all()
    for parent in parent_order:
        for child in parent.child_order.all():
            income_base = OrderIncome.objects.create_referee_income(child)
            if income_base:
                OrderIncome.objects.create_other_income(income_base)


# 创建收益
class CreateIncomeThread(threading.Thread):
    def __init__(self, s_order):
        threading.Thread.__init__(self)
        self.s_order = s_order

    def run(self):  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        # from .models import SupplyOrder
        # s_order = SupplyOrder.objects.get(id=1)
        create_income(self.s_order)


def update_pref(s_order):
    # 增加升级业绩
    relation_users = s_order.user.update_user_perf(s_order.total_fee)
    # 从上级往下级排序
    for i in relation_users:
        # 判断升级
        results = i.level_up_by_sales()
        if results:
            # 判断脱队
            i.drop_out()


# 更新业绩
class UpdatePrefThread(threading.Thread):
    def __init__(self, s_order):
        threading.Thread.__init__(self)
        self.s_order = s_order

    def run(self):  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        update_pref(self.s_order)


# 发送异步通知短信
class SendShortMessageThread(threading.Thread):
    def __init__(self, mobile, content):
        threading.Thread.__init__(self)
        self.content = content
        self.mobile = mobile

    def run(self):  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        response = ShortMessage.mo_short_msg(self.content, self.mobile)
        print(response)


class UntilPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'  # 前端可根据此参数 来动态改变每页展示的数据量
    page_query_param = "p"
    max_page_size = 100

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count_page', math.ceil(self.page.paginator.count / self.page_size)),
            ('count', self.page.paginator.count),
            ('next', self.get_next_link()),
            ('now_page', self.page.number),
            ('previous', self.get_previous_link()),
            ('results', data),
        ]))


class CustomJSONWebTokenAuthentication(JSONWebTokenAuthentication):

    def get_jwt_value(self, request):
        auth = get_authorization_header(request).split()
        auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower()

        if not auth:
            if api_settings.JWT_AUTH_COOKIE:
                return request.COOKIES.get(api_settings.JWT_AUTH_COOKIE)
            return None

        if smart_text(auth[0].lower()) != auth_header_prefix:
            return None

        if len(auth) == 1:
            return None
        elif len(auth) > 2:
            return None

        return auth[1]

    def authenticate(self, request):
        """
        Returns a two-tuple of `User` and token if a valid signature has been
        supplied using JWT-based authentication.  Otherwise returns `None`.
        """
        jwt_value = self.get_jwt_value(request)
        if jwt_value is None:
            return None
        try:
            payload = jwt_decode_handler(jwt_value)
        except Exception as e:
            print(e)
            return None
        user = self.authenticate_credentials(payload)
        return (user, jwt_value)


# 处理商品详情图片
def re_goods_detail_wm(content):
    pic_url = re.findall('src="(.*?)"', content, re.S)
    for i in pic_url:
        yield i
